package edu.geektime.jiangfan.chapter02.common.http;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class OkHttpUtil {
    /**
     * 发起get请求
     *
     * @param url
     * @return
     */
    public static String httpGet(String url) {
        String result = null;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(request).execute();
            result = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 执行同步 Post请求
     * @param url
     * @param jsonStr
     * @param headers
     * @return
     * @throws IOException
     */
    public static Response httpPost(String url, String jsonStr, Map<String, String> headers) throws IOException {
        //构造请求体
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/html;charset=utf-8"), jsonStr);
        //创建requestBody
        Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody);
        //构造请求头
        if(!CollectionUtils.isEmpty(headers)){
            for (Map.Entry<String, String> mapEntry : headers.entrySet()) {
                // value不为空
                if(!Objects.isNull(mapEntry.getValue())){
                    requestBuilder.addHeader(mapEntry.getKey(), String.valueOf(mapEntry.getValue()));
                }
            }
        }
        //构建请求
        Request request = requestBuilder.build();
        //获取client
        OkHttpClient okHttpClient = new OkHttpClient();
        //执行
        Response response = okHttpClient.newCall(request).execute();
        return response;
    }

}
